package com.sgb.merchant.view.activity;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.text.Html;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.tabs.TabLayout;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.IndustryDetailEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.router.PathUser;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivitySelfIndustryDetailBinding;
import com.sgb.merchant.view.adapter.CommPagersAdapter;
import com.sgb.merchant.view.fragment.IndustryApplyFragment;
import com.sgb.merchant.view.fragment.IndustryDynamicFragment;
import com.sgb.merchant.view.fragment.IndustryInfoFragment;
import com.sgb.merchant.view.fragment.IndustryRequireFragment;
import com.sgb.merchant.viewmodel.IndustryViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;


/**
 * @author: 王彬臣
 * @date: 2021/10/13
 * @Description: 我的-产业园区详情
 */
@Route(path = PathMerchant.SelfIndustryDetailActivity)
public class SelfIndustryDetailActivity extends BaseActivity<IndustryViewModel, MerchantActivitySelfIndustryDetailBinding> {
    @Autowired(name = RouterKey.NO, desc = "详情no")
    String no;

    private String[] titles = {"园区基本信息", "园区动态", "园区入驻要求", "入驻申请记录"};
    private final ArrayList<Fragment> mFragment = new ArrayList<>();
    private int currentIndex = 0;
    private FragmentManager fragmentManager;
    IndustryInfoFragment mInfoFrag;
    IndustryDynamicFragment dynamicFragment;
    IndustryRequireFragment industryRequireFragment;
    IndustryApplyFragment industryApplyFragment;
    private int id;
    IndustryDetailEntity mEntity;
    boolean loadFirst = true;

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_self_industry_detail;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(IndustryViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.setClick(this);
        mBinding.includeTitle.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBinding.includeTitle.titleView.setText("产业园区详情");
        //取消tab点击效果
        mBinding.tablayout.setTabRippleColor(ColorStateList.valueOf(getResources().getColor(R.color.transparent)));
        for (String title : titles) {
            mBinding.tablayout.addTab(mBinding.tablayout.newTab().setText(title));
        }
        mBinding.tablayout.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                displayFrg(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mBinding.vpContent.setNoScroll(true);

        initData();


    }

    private void initData() {


        DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
        mViewModel.getSelfDetail(no);
        mViewModel.ldInfo.observe(this, data -> {

            mEntity = data;
            if (mEntity != null) {
                if (loadFirst) {
                    loadFirst = false;
                    initFragment();
                } else {
                    mInfoFrag.refresh(mEntity);
                    dynamicFragment.refresh();
                    industryRequireFragment.refresh(mEntity);
                }
                mBinding.bidLayout.setVisibility(View.VISIBLE);
                mBinding.coordinator.setVisibility(View.VISIBLE);
                mBinding.setViewModel(mEntity);
                if (data.getParkStatus().equals("下架")) {//下架
                    mBinding.tvStatus.setText("下架");
                    mBinding.tvPutAway.setVisibility(View.VISIBLE);
                    mBinding.tvDel.setVisibility(View.VISIBLE);
                    mBinding.tvEdit.setVisibility(View.VISIBLE);
                    mBinding.tvDownAway.setVisibility(View.GONE);

                } else {
                    mBinding.tvStatus.setText("上架");
                    mBinding.tvPutAway.setVisibility(View.GONE);
                    mBinding.tvDel.setVisibility(View.GONE);
                    mBinding.tvEdit.setVisibility(View.GONE);
                    mBinding.tvDownAway.setVisibility(View.VISIBLE);
                }
            }


        });

        mViewModel.ldState.observe(this, state -> {
            switch (state) {//0未上架 1已删除 2正常
                case 1:
                    mBinding.coordinator.setVisibility(View.GONE);
                    mBinding.bidLayout.setVisibility(View.GONE);
                    mBinding.rlError.setVisibility(View.VISIBLE);
                    mBinding.noDataTv.setText(Html.fromHtml("当前数据已删除，请<u><font color='#5892FD'>返回列表</font></u>继续浏览吧~"));
                    mBinding.noDataTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_REFRESH));
                            finish();
                        }
                    });
                    break;


            }
        });

        mViewModel.ldStatus.observe(this, result -> {
            if (!result) {
                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("该数据状态已发生变化，请刷新后再进行操作。")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> mViewModel.getSelfDetail(no)).show();
            }
        });
        mViewModel.ldDoResult.observe(this, result -> {
            if (mEntity.getParkStatus().equals("上架")) {
                mEntity.setParkStatus("下架");
            } else {
                mEntity.setParkStatus("上架");
            }
            mViewModel.ldInfo.postValue(mEntity);
            //刷新列表页
            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_REFRESH));
        });

        mViewModel.ldDel.observe(this, success -> {
            MToast.showToast(SelfIndustryDetailActivity.this,"删除成功");
            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_REFRESH));
            finish();
        });
    }


    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        mInfoFrag = new IndustryInfoFragment();
        mFragment.add(mInfoFrag);
        dynamicFragment = IndustryDynamicFragment.newInstance(no);
        mFragment.add(dynamicFragment);
        industryRequireFragment = new IndustryRequireFragment();
        mFragment.add(industryRequireFragment);
        industryApplyFragment = new IndustryApplyFragment();
        mFragment.add(industryApplyFragment);
        CommPagersAdapter commPagersAdapter=new CommPagersAdapter(fragmentManager,mFragment,titles);
        mBinding.vpContent.setAdapter(commPagersAdapter);
        mBinding.vpContent.setOffscreenPageLimit(titles.length);
        mInfoFrag.refresh(mEntity);
        industryRequireFragment.refresh(mEntity);

    }

    @Override
    public void onClick(View v) {
        id = v.getId();
        if (id == R.id.iv_map) {
            if (mEntity != null) {
                ARouter.getInstance().build(PathUser.MapPositionActivity)
                        .withDouble("latitude", mEntity.getAddressLat())
                        .withDouble("longitude", mEntity.getAddressLng())
                        .withString("companyName", mEntity.getParkName())
                        .withString("address", mEntity.getProvinceName() + mEntity.getCityName() + mEntity.getRegionName() + mEntity.getAddressInfo())
                        .navigation();
            }
        } else if (id == R.id.tv_edit) {

            mViewModel.getDetailState(SelfIndustryDetailActivity.this, no, 0, mEntity);

        } else if (id == R.id.tv_del) {

            mViewModel.getDetailState(SelfIndustryDetailActivity.this, no, 3, mEntity);
        } else if (id == R.id.tv_down_away) {

            mViewModel.getDetailState(SelfIndustryDetailActivity.this, no, 2, mEntity);
        } else if (id == R.id.tv_put_away) {

            mViewModel.getDetailState(SelfIndustryDetailActivity.this, no, 1, mEntity);
        }
    }

    public void displayFrg(int index) {
        mBinding.vpContent.setCurrentItem(index);
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MainEvent event) {
        if (event == null) return;
        if (event.getMessageTag() == EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_DETAIL) {
            DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
            mViewModel.getSelfDetail(no);
        } else if (event.getMessageTag() == EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_DETAIL_FINISH) {
            finish();
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 3000) {
                finish();
            }
        }
    }
}
